package com.cskaoyan.market.controller.wx;

import com.cskaoyan.market.db.domain.MarketCoupon;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.MarketWXAuthService;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("wx/auth")
public class WXAuthController {

    @Autowired
    MarketWXAuthService marketWXAuthService;
    @Autowired
    HttpSession session;

    @PostMapping("login")
    private Object login(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String requestBody = HttpUtil.getRequestBody(request);
        MarketUser marketUser = JacksonUtil.getObjectMapper().readValue(requestBody, MarketUser.class);
        List<MarketUser> marketUsers = marketWXAuthService.login(marketUser);
        if (marketUsers.size()<=0) {
            Object o = ResponseUtil.wrongUsernameOrPassword();
            return o;
        }

        MarketUser marketUserIdent = marketUsers.get(0);
        session.setAttribute("admin",marketUserIdent);
        HashMap<String, Object> data = new HashMap<>();
        data.put("userInfo",marketUserIdent);
        data.put("token",session.getId());
        Object ok = ResponseUtil.ok(data);
        return ok;
    }

    @PostMapping("logout")
    private Object logout(){
        session.invalidate();
        Object ok = ResponseUtil.ok();
        return ok;
    }
}
